package cn.kent.high.questions.threadLocal;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池中使用threadLocal需要及时清理，否则会导致引用一直存在，从而导致内存溢出
 * 通过注释 localVariable.remove(); 观察jconsole的内存表盘
 */
public class ThreadPollTest {
    static class LocalVariable {
        private Long[] a = new Long[1024 * 1024];
    }

    final static ThreadPoolExecutor threadPoolExecutor =
            new ThreadPoolExecutor(5, 5, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(500));
    final static ThreadLocal<LocalVariable> localVariable = new ThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 50; i++) {
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    localVariable.set(new LocalVariable());
                    System.out.println("use local variable");
                    localVariable.remove();
                }
            });
            Thread.sleep(1000);
        }
        System.out.println("thread pool over!");
    }
}
